import os.path
import sys

sys.path.append(os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__)))))

import click

from dp_analysis.analysis.base import RecommendBase
from dp_analysis.db.connection import Mysql
from dp_analysis.utils.data_search import search_region, search_cuisine
from dp_analysis.utils.decorate import decorate


class ShopRecommend(RecommendBase):
    """
    为吃货推荐餐厅
    """

    def __init__(self):
        super().__init__()

    @decorate(obj_name="ShopRecommend")
    def analyse(self, db, region, cuisine, location, distance, price, comment):
        location = self.calc_lat_lng(location)
        if not location:
            raise Exception("输入详细地址无法获取地理坐标系，请重新输入...")
        with Mysql("dp", db) as mysql:
            connection = mysql.engine.connect()
            recommend_number = 0
            for shop_id, shop_name, category, business_hours, average_price, comment_number, lng, lat \
                    in self.query(connection, region, cuisine):
                if (not lng) or (not lat):
                    continue
                dis = self.calc_distance(location, (lat, lng))
                if dis > float(distance):
                    continue
                if (not int(price, 0)) or float(average_price) > float(price):
                    continue
                if float(comment_number) < float(comment):
                    continue

                recommend_number += 1
                print(f"推荐餐厅："
                      f"店铺ID {self.output(shop_id)} ，"
                      f"店铺名称 {self.output(shop_name)} ，"
                      f"所属菜系 {self.output(category)} ，"
                      f"评论数量 {self.output(comment_number)} ，"
                      f"营业时间 {self.output(business_hours)}，"
                      f"距离 {self.output('%.2f' % dis + 'km')} ，"
                      f"人均价格 {self.output(average_price)} 元！")

            if not recommend_number:
                print(self.output("所选条件无推荐餐厅！"))
            else:
                print(f"所选条件共存在 {self.output(recommend_number)} 家推荐餐厅！")

    @staticmethod
    def query(connection, region, cuisine):
        sql = f"SELECT " \
              f"shop_id, shop_name, category, business_hours, average_price, comment_number, lng, lat " \
              f"FROM shop_info " \
              f"WHERE region={region!r} " \
              f"AND category IN ({cuisine})" \
              f"AND lat != ''" \
              f"AND lng != '';"
        return connection.execute(sql)


@click.command()
@click.option("--db", default=0, help="请选择使用的数据库")
@click.option("--region", prompt="地区", help="12大地区通过helpers.py获取\n只能指定单个地区")
@click.option("--cuisine", prompt="菜系", help="各地区所有菜系通过helpers.py获取\n若指定多个以英文逗号分割\nall指定全部")
@click.option("--location", prompt="所在区域", help="请输入当前所在的详细地址")
@click.option("--distance", prompt="区域半径（单位：KM）", help="查找区域半径（单位：KM）")
@click.option("--price", prompt="参考人均价位（单位：元）", help="请输入最高价格（单位：元）")
@click.option("-comment", "--comment_number", prompt="评论数量", help="请输入参考餐厅的最小评论量")
def main(db, region, cuisine, location, distance, price, comment_number):
    if region not in search_region(db):
        raise Exception("输入地区不再可选范围！")

    if cuisine == "all":
        cuisine = search_cuisine(db, region)
    else:
        cuisine = cuisine.split(',')
    cuisine = ','.join([f"{cui.strip()!r}" for cui in cuisine])

    shop_recommend = ShopRecommend()
    shop_recommend.analyse(db, region, cuisine, location, distance, price, comment_number)


if __name__ == '__main__':
    # 运行参考如下：
    # python shop_recommend.py --db 0 --region 北京 --cuisine 北京菜,川菜,湘菜 --location 北京市海淀区中关村中钢国际广场 --distance 1 --price 100 -comment 1000
    # python shop_recommend.py --db 0 --region 北京 --cuisine all --location 北京市海淀区中关村中钢国际广场 --distance 1.5 --price 100 -comment 1000
    main()
